package com.xiaobai.netease_news.activities;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;


import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.xiaobai.netease_news.R;
import com.xiaobai.netease_news.model.Common;
import com.xiaobai.netease_news.model.Mp3Data;
import com.xiaobai.netease_news.model.PlayerResponseData;
import com.xiaobai.netease_news.model.VideoData;
import com.xiaobai.netease_news.utils.CommonHttpUtil;
import com.xiaobai.netease_news.utils.Player;
import com.xiaobai.netease_news.utils.RequestManager;
import com.xiaobai.netease_news.utils.ViewHolder;
import com.xiaobai.netease_news.views.CircleProgressBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;

public class PlayerActivity extends Activity implements AdapterView.OnItemClickListener, View.OnClickListener {
    List<Common> commonList;
    private String tid;
    private MyAdapter adapter;
    private ListView listView;
    private String cover;
    private ImageView imagePlayer;
    private TextView txtCommentCount;
    private int replayCount;
    private ImageView imageSign;
    private TextView txtContent;
    private String url_m3u8;
    private MediaPlayer mediaPlayer;
    private ImageView imagePause;
    private ImageView imageBack;
    private String docid2;
    private SeekBar musicProgress;
    private Player player;
    private CircleProgressBar circleProgressBar;
    private boolean isProgressBarShow;
    private ImageView nextMusic;
    private ImageView preMusic;
    private int currentPosition;
    private Animation animation;
    private TextView txtStartTime;
    private TextView txtEndTime;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        commonList = new LinkedList<>();
        adapter = new MyAdapter(commonList);
        listView = (ListView) findViewById(R.id.player_listView);
        imagePlayer = (ImageView) findViewById(R.id.player_image);
        imagePlayer.setImageResource(R.mipmap.biz_audio_play_header_column_cover_default);
        txtCommentCount = (TextView) findViewById(R.id.player_comment);
        imagePause = (ImageView) findViewById(R.id.player_pause);
        imagePause.setOnClickListener(this);
        imageBack = (ImageView) findViewById(R.id.player_back);
        imageBack.setOnClickListener(this);
        nextMusic = (ImageView) findViewById(R.id.player_right_image);
        nextMusic.setOnClickListener(this);
        preMusic = (ImageView) findViewById(R.id.player_left_image);
        preMusic.setOnClickListener(this);
        txtStartTime = (TextView) findViewById(R.id.player_start_time);
        txtEndTime = (TextView) findViewById(R.id.player_end_time);
        Intent intent = getIntent();
        tid = intent.getStringExtra("tid");
        Log.d("tid", "tid:" + tid);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        musicProgress = (SeekBar) findViewById(R.id.music_progress);
        player = new Player(musicProgress);
        mediaPlayer = player.mediaPlayer;
        musicProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
        circleProgressBar = (CircleProgressBar) findViewById(R.id.player_load_progress);
        if (!isProgressBarShow){
            circleProgressBar.setVisibility(View.VISIBLE);
        }else {
            circleProgressBar.setVisibility(View.GONE);
        }
        isProgressBarShow = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (tid!=null) {
            PlayerContentAsynTask asynTask = new PlayerContentAsynTask();
            asynTask.execute(tid);
        }
//        RequestQueue requestQueue = RequestManager.getInstance(this).getRequestQueue();
//        JsonObjectRequest request = new JsonObjectRequest(
//                url,
//                null,
//                new Response.Listener<JSONObject>() {
//                    @Override
//                    public void onResponse(JSONObject jsonObject) {
//                        PlayerResponseData responseData = new PlayerResponseData();
//                        responseData.parseJSON(jsonObject, tid);
//                        List<Common> commonLists = responseData.getCommonList();
//                        commonList.addAll(0, commonLists);
//                        adapter.notifyDataSetChanged();
//                    }
//                },
//                new Response.ErrorListener() {
//                    @Override
//                    public void onErrorResponse(VolleyError volleyError) {
//                        volleyError.printStackTrace();
//                    }
//                }
//        );
//        requestQueue.add(request);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        currentPosition = position;
        final String docid = commonList.get(position).getDocid();
        Object tag = view.getTag();
        if (tag!=null&&tag instanceof Integer) {
            Integer it = (Integer) tag;
            ImageView imageView = (ImageView) listView.getChildAt(it).findViewById(R.id.player_item_image);
            imageView.setVisibility(View.VISIBLE);
            TextView textView = (TextView) listView.getChildAt(it).findViewById(R.id.player_item_content);
            textView.setTextColor(Color.RED);
        }
        imagePlayer.setVisibility(View.GONE);
        imagePause.setVisibility(View.GONE);
        circleProgressBar.setVisibility(View.VISIBLE);


        PlayerAsynTask playerAsynTask = new PlayerAsynTask();
        playerAsynTask.execute(docid);
        //        String url = "http://c.m.163.com/nc/article/" + docid + "/full.html";
//        RequestQueue requestQueue = RequestManager.getInstance(this).getRequestQueue();
//        JsonObjectRequest request = new JsonObjectRequest(
//                url,
//                null,
//                new Response.Listener<JSONObject>() {
//                    @Override
//                    public void onResponse(JSONObject jsonObject) {
//                        Mp3Data mp3Data = new Mp3Data();
//                        mp3Data.parseJSON(jsonObject, docid);
//                        List<VideoData> videoList = mp3Data.getVideoList();
//                        Log.d("VideoList", "VideoList:" + videoList);
//                        if (!videoList.isEmpty()) {
//                            cover = videoList.get(0).getCover();
//                            url_m3u8 = videoList.get(0).getUrl_m3u8();
//                            replayCount = mp3Data.getReplayCount();
//                            docid2 = mp3Data.getDocid();
//                        }
//                    }
//                },
//                new Response.ErrorListener() {
//                    @Override
//                    public void onErrorResponse(VolleyError volleyError) {
//                        volleyError.printStackTrace();
//                    }
//                }
//
//        );
//        requestQueue.add(request);
//        Log.d("cover", "cover:" + cover);


    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.player_pause:
                if (mediaPlayer.isPlaying()) {
                    imagePause.setImageResource(R.mipmap.biz_audio_btn_play);
                    player.pause();
                    animation.cancel();
                } else {
                    imagePause.setImageResource(R.mipmap.biz_audio_btn_pause);
                    player.play();
                    animation.start();
                }
                break;
            case R.id.player_back:
                finish();
                break;
            case R.id.player_left_image:
                currentPosition--;
                if (currentPosition<0){
                    currentPosition=0;
                }
                String docid = commonList.get(currentPosition).getDocid();
                circleProgressBar.setVisibility(View.VISIBLE);
                imagePause.setVisibility(View.GONE);
                imagePlayer.setVisibility(View.GONE);
                PlayerAsynTask playerAsynTask = new PlayerAsynTask();
                playerAsynTask.execute(docid);
                break;
            case R.id.player_right_image:
                currentPosition++;
                if (currentPosition>commonList.size()-1){
                    currentPosition=commonList.size()-1;
                }
                String docid2 = commonList.get(currentPosition).getDocid();
                circleProgressBar.setVisibility(View.VISIBLE);
                imagePause.setVisibility(View.GONE);
                imagePlayer.setVisibility(View.GONE);
                playerAsynTask = new PlayerAsynTask();
                playerAsynTask.execute(docid2);
                break;
        }
    }


    class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
        int progress;

        @Override
        public void onProgressChanged(SeekBar seekBar, final int progress,
                                      boolean fromUser) {
            // 原本是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()
            this.progress = progress * player.mediaPlayer.getDuration()
                    / seekBar.getMax();
//            mediaPlayer.seekTo(progress);

            int duration = player.mediaPlayer.getDuration()/1000;
            int minutes = duration/60;
            int seconds = duration%60;
            minutes = minutes%60;
            txtEndTime.setText(minutes+":"+seconds);
                    int time = progress/1000;
                    int minutes2 = time/60;
                    int seconds2 = time%60;
                    minutes2 = minutes2%60;
                    txtStartTime.setText(minutes2 + ":" + seconds2);


        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // seekTo()的参数是相对与影片时间的数字，而不是与seekBar.getMax()相对的数字
            player.mediaPlayer.seekTo(progress);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mediaPlayer.stop();
    }

    private class PlayerAsynTask extends AsyncTask<String,Void,JSONObject>{
        private String id = null;
        @Override
        protected JSONObject doInBackground(String... params) {
            id = params[0];
        String url = "http://c.m.163.com/nc/article/" + params[0] + "/full.html";
            byte[] bytes = CommonHttpUtil.doGet(url);
            try {
                String string = new String(bytes, "utf-8");
                return new JSONObject(string);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            if (circleProgressBar.getVisibility()==View.VISIBLE){
                circleProgressBar.setVisibility(View.GONE);
                imagePause.setVisibility(View.VISIBLE);
                imagePlayer.setVisibility(View.VISIBLE);
            }
            imagePause.setImageResource(R.mipmap.biz_audio_btn_pause);
            Mp3Data mp3Data = new Mp3Data();
            mp3Data.parseJSON(jsonObject, id);
            List<VideoData> videoList = mp3Data.getVideoList();
            Log.d("VideoList", "VideoList:" + videoList);
            if (!videoList.isEmpty()) {
                cover = videoList.get(0).getCover();
                url_m3u8 = videoList.get(0).getUrl_m3u8();
                replayCount = mp3Data.getReplayCount();
                docid2 = mp3Data.getDocid();
            }

            if (cover != null) {
                ImageLoader imageLoader = RequestManager.getInstance(PlayerActivity.this).getImageLoader();
                imageLoader.get(
                        cover,
                        imageLoader.getImageListener(imagePlayer, R.mipmap.ic_launcher, R.mipmap.ic_launcher)
                );
                animation = AnimationUtils.loadAnimation(PlayerActivity.this, R.anim.anim_rotate);
                imagePlayer.setAnimation(animation);
                imagePlayer.startAnimation(animation);
                Log.d("replayCount", "replayCount:" + url_m3u8);
                txtCommentCount.setText(String.valueOf(replayCount) + "跟帖");
                if (url_m3u8 != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            player.playUrl(url_m3u8);
                        }
                    }).start();
                }



            }


        }
    }

    private class PlayerContentAsynTask extends AsyncTask<String,Void,JSONObject>{

        @Override
        protected JSONObject doInBackground(String... params) {
            String url = "http://c.m.163.com/nc/article/list/" + params[0] + "/0-20.html";
            byte[] bytes = CommonHttpUtil.doGet(url);
            try {
                String strJSON = new String(bytes, "utf-8");
                return new JSONObject(strJSON);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            if (circleProgressBar.getVisibility()==View.VISIBLE){
                circleProgressBar.setVisibility(View.GONE);
            }
            imagePause.setImageResource(R.mipmap.biz_audio_btn_play);
            PlayerResponseData responseData = new PlayerResponseData();
            responseData.parseJSON(jsonObject, tid);
            List<Common> commonLists = responseData.getCommonList();
            commonList.addAll(0, commonLists);
            adapter.notifyDataSetChanged();
        }
    }


    private class MyAdapter extends BaseAdapter{
        List<Common> commonList;

        public MyAdapter(List<Common> commonList) {
            this.commonList = commonList;
        }

        @Override
        public int getCount() {
            int ret = 0;
            if (commonList != null) {
                ret = commonList.size();
            }
            return ret;
        }

        @Override
        public Object getItem(int position) {
            Object ret = null;
            if (commonList != null) {
                ret = commonList.get(position);
            }
            return ret;
        }

        @Override
        public long getItemId(int position) {
            long ret = 0;
            if (commonList != null) {
                ret = position;
            }
            return ret;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View ret = null;
            if (convertView != null) {
                ret = convertView;
            } else {
                ret = LayoutInflater.from(PlayerActivity.this).inflate(R.layout.player_adapter_item, parent, false);
            }
            txtContent = ViewHolder.getView(ret, R.id.player_item_content);
            txtContent.setTag(position);
            imageSign = (ImageView) ret.findViewById(R.id.player_item_image);
            imageSign.setTag(position);
            TextView txtTitme = ViewHolder.getView(ret, R.id.player_item_time);
            if (!commonList.isEmpty()) {
                String title = commonList.get(position).getTitle();
                Log.d("title", "title:" + title);
                txtContent.setText(title);
                String ptime = commonList.get(position).getPtime();
                String[] split = ptime.split(" ");
                txtTitme.setText(split[0]);
            }

            return ret;
        }




    }
}
